package com.sxdz.exception

import com.sxdz.constant.CommonConstant
import org.springframework.core.annotation.AnnotationUtils
import org.springframework.web.bind.annotation.ControllerAdvice
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.ResponseStatus
import org.springframework.web.servlet.ModelAndView

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 * Created by zb on 2015/6/12.
 */

@ControllerAdvice
class GlobalControllerExceptionHandler {

    /**
     * 验证异常捕捉
     * @param req
     * @param res
     * @param e
     * @return
     */
    @ExceptionHandler(org.springframework.validation.BindException.class)
    handleConflict(HttpServletRequest req, HttpServletResponse res, org.springframework.validation.BindException e) {
        /*
        e.model.each {String key,Object val->
            if (val instanceof  BeanPropertyBindingResult){
                (val  as BeanPropertyBindingResult).fieldErrors.each {FieldError it->
                    println it.field
                }

            }
        }*/
        req.getRequestDispatcher("/error/"+CommonConstant.ErrorMsg.E9001.value).forward(req, res)
        return new ModelAndView()
    }

    /**
     * 其它错误信息
     * @param req
     * @param e
     * @return
     * @throws Exception
     */
    @ExceptionHandler(value = Exception.class)
    defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {

        if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null)
            throw e;

        ModelAndView mav = new ModelAndView();
        mav.addObject("exception", e);
        mav.addObject("url", req.getRequestURL());
        //mav.setViewName(DEFAULT_ERROR_VIEW);
        return new ModelAndView()
    }


}
